<?php
namespace app\nadmin\controller;
use think\Validate;
use app\nadmin\model\Adminer_M;

/**
 * @explain 管理员列表相关操作类
 * @time 2019/3/28
 * @writer liuhao
 */

class Adminer extends Base
{

    //模型实例
    protected $adminer_M;
    //每页记录数 默认为10
    protected $perpage = 10;

    //初始化模型
    protected function initialize()
    {
        $this->adminer_M = new adminer_M();
    }

    /*
     * @explain 系统列表页
     */
    public function index()
    {
        return $this->fetch();
    }

    //加载列表数据
    public function getAdminerList()
    {
        //页码
        $page = $this->request->page?$this->request->page:1; //页码
        $perpage = $this->request->limit ? $this->request->limit :$this->perpage; //每页记录数
        //数据验证
        $rule = [
            'page' => 'number|gt:0',
            'perpage' => 'number|gt:0',
        ];
        $msg = [
            'page.integer' => '页码参数必须为整数',
            'page.gt' => '页码参数必须大于0',
            'perpage.integer' => '每页记录数参数必须为整数',
            'perpage.gt' => '每页记录数参数必须大于0',
        ];
        $data = ['page'=>$page,'perpage'=>$perpage];
        $validate = Validate::make($rule,$msg);
        $re = $validate->check($data);
        if(!$re)
        {
            return echojson($validate->getError(),0);
        }

        $start = ($page-1) * $perpage;
        $limit = $start.','.$perpage;


        $field = "id,role_id,username,status,ctime,name,phone,email";
        $list = $this->adminer_M->getMore($field,$where = [],$order = [],$limit);
        //获取角色信息

        $roleIds = $this->roleIds($list); //角色ID集合
        if($roleIds)
        {
            $field = 'id,role';
            $where = ['id'=>$roleIds];
            $roleList = $this->getRoleMore($field,$where,$order = [],$limit='');
            //拼接数据
            if($roleList)
            {
                $list = $this->recombineData($list,$roleList);
            }
        }
        //获取个数
        $count = $this->adminer_M->getCount();
        return laytable($count,$list);
    }

    //编辑操作获取单个数据
    public function AdminerEdit()
    {
        $id = $this->request->id;
        $validate = Validate::make(['id'=>'integer|gt:0'],['id.integer'=>'参数异常 E001','id.gt'=>'参数异常 E002']);
        $re = $validate->check(['id'=>$id]);
        if(!$re)
        {
            return echojson($validate->getError(),0);
        };

        $where = ['id'=>$id];
        $field = "id,role_id,username,status,ctime,name,phone,email";
        $list = $this->adminer_M->getOne($field,$where);
        return echojson('success',1,$list);
    }

    //编辑操作
    public function doEdit()
    {
        //参数
        $id = $this->request->id;
        $status =$this->request->status;
        $username =$this->request->username;
        $pwd = isset($this->request->pwd)?$this->request->pwd:''; //密码为空表示不修改密码
        $name =$this->request->name;
        $phone =$this->request->phone;
        $email =$this->request->email;
        $role_id = $this->request->role_id;

        //验证
        $rule = [
            'id' => 'number|gt:0|require',
            'status' => 'in:0,1',
            'username'=> 'require|alphaDash|min:6|max:12', //汉字字母数字下划线
            'name' =>'require|chsDash|min:2|max:16', //字母数字下划线
            'phone' => 'mobile',
            'email' =>'require|email', //字母数字下划线
            'role_id' => 'require|gt:-1'
        ];
        $msg = [];
        $data = [
            'id'=>$id,
            'status'=>$status,
            'username'=> $username,
            'pwd' =>$pwd,
            'name' =>$name,
            'phone' => $phone,
            'email' =>$email,
            'role_id' => $role_id
        ];

        //判断密码是否为空
        if($pwd)
        {
            $rule['pwd'] = 'alphaDash|min:6|max:12'; //字母数字下划线
            $data['pwd'] = $pwd;
        }
        $validate = Validate::make($rule,$msg);
        $re = $validate->check($data);
        if(!$re)
        {
            return echojson($validate->getError(),0);
        }

        $where = ['id'=>$id];
        if($pwd) {
            //密码盐
            $salt = getRandStr($num = 6, $str = '');
            //密码
            $data['pwd'] = createPwd($pwd, $salt);
            $data['salt'] = $salt;
        }
        $re = $this->adminer_M->editOne($data,$where);
        if($re){
            return echojson("修改成功",1);
        }else{
            return echojson("修改失败",0);
        }
    }

    //添加单条操作
    public function doAdd()
    {
        //参数
        $status =$this->request->status;
        $username =$this->request->username;
        $pwd =$this->request->pwd;
        $name =$this->request->name;
        $phone =$this->request->phone;
        $email =$this->request->email;
        $role_id = $this->request->role_id;
        $now = date('Y-m-d H:i:s',time());

        //验证
        $rule = [
            'status' => 'in:0,1',
            'username'=> 'require|alphaDash|min:6|max:12', //字母数字下划线
            'pwd' =>'require|alphaDash|min:6|max:12', //字母数字下划线
            'name' =>'require|chsDash|min:2|max:16', //汉字字母数字下划线
            'phone' => 'mobile',
            'email' =>'require|email', //字母数字下划线
            'role_id' => 'require|gt:-1|number'
        ];
        $msg = [];
        $data = [
            'status'=>$status,
            'username'=> $username,
            'pwd' =>$pwd,
            'name' =>$name,
            'phone' => $phone,
            'email' =>$email,
            'role_id' => $role_id
        ];
        $validate = Validate::make($rule,$msg);
        $re = $validate->check($data);
        if(!$re)
        {
            return echojson($validate->getError(),0);
        }
        //操作
        $data['ctime'] = $now;
        //密码盐
        $salt = getRandStr($num=6,$str='');
        //密码
        $data['pwd'] = createPwd($pwd,$salt);
        $data['salt'] = $salt;
        $re = $this->adminer_M->insertOne($data);
        if($re){
            return echojson("添加成功",1);
        }else{
            return echojson("添加失败",0);
        }
    }
    //编辑 状态操作
    public function changeStatus()
    {
        //参数
        $id = $this->request->id;
        $status = $this->request->status;
        //验证参数
        $rule = [
            'id' => 'require|gt:0|number',
            'status' => 'in:0,1',
        ];
        $msg = [
            'id.integer' => '参数ID必须为整数',
            'id.gt '=> '参数ID必须大于0',
            'status.in' => '参数status只能为0,1之间',
        ];
        $data = [
            'id' => $id,
            'status' => $status,
        ];
        $validate = Validate::make($rule,$msg);
        $re = $validate->check($data);
        if(!$re)
        {
            return echojson($validate->getError(),0);
        }

        //编辑
        $where = ['id'=>$id];
        $data = ['status'=>$status];
        $result = $this->adminer_M->editOne($data,$where);
        if($result)
        {
            return echojson("修改成功",1);
        }else{
            return echojson("修改失败",0);
        }
    }

    //删除单条记录
    public function delOne()
    {
        $id = $this->request->id;
        //验证数据
        $validate = Validate::make(['id' => 'integer|gt:0'],[]);
        $re = $validate->check(['id'=>$id]);
        if(!$re)
        {
            return echojson($validate->getError(),0);
        }

        $where = ['id'=>$id];
        $result = $this->adminer_M->delOne($where);
        if($result)
        {
            return echojson('删除成功',1);
        }else{
            return echojson('删除失败',0);
        }
    }
    //删除多条记录
    public function delMore()
    {
        $idStr = $this->request->idStr;
        //验证规则
        $rule = [
            'idStr' => ['regex' => '/^(([1-9]\d*)|(([1-9]\d*,)+[1-9]\d*))$/','require'],
        ];
        $validate = Validate::make($rule,[]);
        $re = $validate->check(['idStr'=>$idStr]);
        if(!$re)
        {
            return echojson($validate->getError(),0);
        }

        $where = "id in ($idStr)";
        $result = $this->adminer_M->delMore($where);
        if($result)
        {
            return echojson('删除成功',1);
        }else{
            return echojson('删除失败',0);
        }
    }


    /*
     * @explain 获取角色信息列表数据
     */
    protected function getRoleMore($field='',$where = [],$order = [],$limit='')
    {
        $role = new Role();
        $list = $role->getMore($field,$where,$order,$limit);
        return $list;
    }

    //获取角色信息
    public function getRoleInfo()
    {
        $field = "id,role";
        $where = "status=1";

        $list = $this->getRoleMore($field,$where,$order = [],$limit='');
        return echojson("OK",1,$list);
    }

    /* @explain 从多条管理员数据中获取 角色id集合
     * @param $list [] 管理员列表
     * @return []
     */
    protected function roleIds($list)
    {
        $arr = [];
        if(is_array($list) && $list) {
            foreach ($list as $v)
            {
                $arr[] = $v['role_id'];
            }
            //去重
            $arr = array_unique($arr);
            return $arr;
        }
        return [];
    }

    /* @explain 将管理员和角色数据合并成新的数组返回
     * @param $list [] 管理员列表，$roleList [] 角色列表
     * @return [];
     */
    protected function recombineData($list,$roleList)
    {
        if(is_array($list) && is_array($roleList))
        {
            $newRoleList = array_column($roleList,'role','id');
            foreach($list as &$v)
            {
                $v['role'] = isset($newRoleList[$v['role_id']])?$newRoleList[$v['role_id']]:"";
            }
            return $list;
        }
        return [];
    }

    /*
     * @explain 修改单个管理员的角色
     */
    public function editRoleOne()
    {
        $id =$this->request->id;
        $role_id = $this->request->role_id;

        $rule = [
            'id'=>'require|number|gt:0',
            'role_id'=>'require|number',
        ];
        $data = [
            'id'=>$id,
            'role_id'=>$role_id
        ];
        $validate = Validate::make($rule,[]);
        if(!$validate->check($data))
        {
            return echojson($validate->getError(),0);
        }

        $re = $this->adminer_M->editOne(['role_id'=>$role_id],"id=$id");
        if($re){
            return echojson("移除成功",1);
        }else{
            return echojson("移除失败",0);
        }
    }
}